package com.youlai.netty.service.tcp;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
/**
 * 自定义解码器
 * @author zc
 * @date 2023-01-30 23:49
 */
@Slf4j
public class MyMessageDecoder extends ByteToMessageDecoder{

    /**
     * 协议开始符
     */
    private String prefix = "{";
    /**
     * 协议结束符
     */
    private String suffix = "}";

    /**
     * 测试数据
     * {
     *     "id": 1,
     *     "time": "2023-02-01 23:36:24",
     *     "body": "l0h58jygus"
     * }
     * @param ctx           the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
     * @param buffer            the {@link ByteBuf} from which to read data
     * @param out           the {@link List} to which decoded messages should be added
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out){
        try {
            if (buffer.readableBytes() > 0) {
                // 待处理的消息包
                byte[] bytesReady = new byte[buffer.readableBytes()];
                buffer.readBytes(bytesReady);
                String s = new String(bytesReady);
                if(s.startsWith(prefix) && s.endsWith(suffix)){
                    MyMessageProtocol protocol = JSONUtil.toBean(s, MyMessageProtocol.class);
                    out.add(protocol);
                }else{
                    log.info("收到客户端数据:{},格式错误无法解码",s);
                }
            }
        }catch(Exception ex) {
          log.error("解码异常:{}", ex.getMessage());
        }
    }


}
